import React from 'react'
import { Card, Button, Modal, Select, Input, Form, Tree, Transfer } from 'antd';
import axios from './../../axios'
import Utils from './../../utils/utils'
import ETable from './../../components/ETable'
// 这是导入权限树结构需要的数据
import menuConfig from './../../config/menuConfig'

const Option = Select.Option;
const FormItem = Form.Item;
const TreeNode = Tree.TreeNode;
class Permission extends React.Component {

    state = {
        isVisible: false,
        isPermissionVisible: false,
        isUserVisible: false
    }

    componentDidMount(){
        axios.requestList(this, '/role/list',{})
    }

    //1.1创建角色
    handleCreateRole=()=>{
            this.setState({
                isVisible: true,
            })
    }
    //1.2.模态框里的角色提交
    handleOk = () => {
        //拿到form表单准备提交的值
        let data = this.roleForm.props.form.getFieldsValue()
        axios.ajax({
            url: '/role/create',
            data: {
                params: data
            }
        }).then((res)=>{
            if(res.code == 0){
                this.setState({
                    isVisible:false
                })
                this.roleForm.props.form.resetFields()
                //modal 框提交过后，重新刷新表单
                axios.requestList(this, '/role/list',{})
            }
        })
    }

    //2.1. 权限设置功能按钮
    handlePermission=()=>{
        let item = this.state.selectedItem;
        if(!item){
            Modal.info({
                title: '温馨提示',
                content: '请选择一个角色'
            })
            return;
        }
        this.setState({
            isPermissionVisible: true,
            detailInfo: item,
            menuInfo: item.menus
        })
    }

    //2.2.权限提交
    handlePremissionSubmit=()=>{
        let permiData = this.PermiForm.props.form.getFieldsValue()
        permiData.role_id = this.state.selectedItem.id;
        permiData.menus = this.state.menuInfo
        axios.ajax({
            url: '/permission/edit',
            data: {
                params: {...permiData}
            }
        }).then((res)=>{
            if(res){
                this.setState({
                    isPermissionVisible: false
                })
                axios.requestList(this, '/role/list',{})  
            }
        })
    }

    //3.1用户授权按钮
    handleuserAuth=()=>{
        let item = this.state.selectedItem;
        if(!item){
            Modal.info({
                title: '温馨提示',
                content: '未选中任何项目'
            })
            return;
        }
        this.setState({
            isUserVisible: true,
            detailInfo: item
        })
        this.getRoleUserList(item.id)

    }

    getRoleUserList = (id) => {
        axios.ajax({
            url: '/role/user_list',
            data: {
                params: {
                    id: id
                }
            }
        }).then((res)=>{
            if(res){
               this.getAuthUserList(res.result) 
            }
        })
    }

    //3.2筛选目标用户
    getAuthUserList=(dataSource)=>{
        const mockData = [];  //定义的数据源
        // selectedKeys	设置哪些项应该被选中 onSearchChange	搜索框内容时改变时的回调函数
        // targetKeys	显示在右侧框数据的key集合 onChange	选项在两栏之间转移时的回调函数
        // onSelectChange	选中项发生改变时的回调函数
        const targetKeys = [];
        if(dataSource && dataSource.length > 0){
            for(let i=0; i<dataSource.length; i++){
                const data={
                    key: dataSource[i].user_id,
                    title: dataSource[i].user_name,  //呈现的名称
                    status: dataSource[i].status
                }
                // 根据状态值判断在右边还是左边
                if(data.status == 1){
                    targetKeys.push(data.key)
                }
                    mockData.push(data);
            }
            this.setState({
                targetKeys,
                mockData
           })
        }

    }
    disPatch = (targetKeys) => {
        this.setState({
            targetKeys: targetKeys
        });
    };
    //3.3 提交
    handleUserSubmit=()=>{
        let data = {}
        data.user_ids = this.state.targetKeys || [];
        data.role_id = this.state.selectedItem.id;
        axios.ajax({
            url: '/role/user_role_edit',
            data: {
                params: {
                    ...data
                }
            }
        }).then((res)=>{
            if(res) {
                this.setState({
                    isUserVisible: false
                })
                axios.requestList(this, '/role/list',{})   
            }
        })
    }
    
    render() {
        const columns = [
            {
                title: '角色ID',
                dataIndex: 'id'
            },{
                title: '角色名称',
                dataIndex: 'role_name'
            },{
                title: '创建时间',
                dataIndex: 'create_time',
                render: Utils.formateDate
            },{
                title: '使用状态',
                dataIndex: 'status',
                render(status){
                    return status==1 ? '启用': '停用'
                }
            },{
                title: '授权时间',
                dataIndex: 'authorize_time',
                render: Utils.formateDate
            },{
                title: '授权人',
                dataIndex: 'authorize_user_name'
            }
        ]
        return (
            <div>
               <Card className="wrap-button" >
                   <Button type="primary" onClick={this.handleCreateRole}>创建角色</Button>
                   <Button type="primary" onClick={this.handlePermission}>设置权限</Button>
                   <Button type="primary" onClick={this.handleuserAuth}>用户授权</Button>
               </Card>
               <div className="content-wrap">
                   <ETable 
                        updateSelectedItem={Utils.updateSelectedItem.bind(this)}
                        selectedRowKeys = {this.state.selectedRowKeys}
                        columns={columns}
                        dataSource={this.state.list}
                   />
               </div>
               <Modal
                title="创建角色"
                visible={this.state.isVisible}
                onOk={this.handleOk}
                onCancel={()=> {
                    this.roleForm.props.form.resetFields()
                    this.setState({
                        isVisible:false
                    })

                }}
               >
                <RoleForm wrappedComponentRef={(inst)=>this.roleForm = inst}/>
               </Modal>
               {/* 权限模态框 */}
               <Modal
                title="权限设置"
                visible={this.state.isPermissionVisible}
                onOk={this.handlePremissionSubmit}
                onCancel={()=> {
                    // this.roleForm.props.form.resetFields()
                    this.setState({
                        isPermissionVisible:false
                    })

                }}
               >
                <PreEditForm 
                wrappedComponentRef={(inst)=>this.PermiForm = inst}
                detailInfo={this.state.detailInfo}
                menuInfo={this.state.menuInfo}
                patchMenuInfo={(checkedKeys)=>{
                    this.setState({
                        menuInfo: checkedKeys
                    })
                }}
                 />
               </Modal>
               {/* 用户授权 */}
               <Modal
                title="用户授权"
                width={800}
                visible={this.state.isUserVisible}
                onOk={this.handleUserSubmit}
                onCancel={()=> {
                    // this.roleForm.props.form.resetFields()
                    this.setState({
                        isUserVisible:false
                    })

                }}
               >
                <RoleAuthForm 
                wrappedComponentRef={(inst)=>this.roleForm = inst}
                detailInfo={this.state.detailInfo}
                targetKeys={this.state.targetKeys}
                mockData={this.state.mockData}
                disPatch={(targetKeys)=>{
                    this.setState({
                        targetKeys
                    })
                }}
                />
               </Modal>
            </div>
        )
    }
}

class RoleForm extends React.Component{
   
    render() {
        const { getFieldDecorator } = this.props.form;
        //设置布局模式
        const FormLayout = {
            labelCol: {
                span: 5
            },
            wrapperCol: {
                span: 19
            }
        }
        
        return(
            <Form layout="horizontal">
                 <FormItem label="角色名称" {...FormLayout}>
                    {
                        getFieldDecorator('role_name')(
                            <Input type="text" placeholder="请输入角色名称"/>
                        )
                    }
                </FormItem>
                <FormItem label="状态" {...FormLayout}>
                    {
                        getFieldDecorator('statu')(
                            <Select placeholder="开启">
                                <Option value={1}>开启</Option>
                                <Option value={2}>关闭</Option>
                            </Select>
                        )
                    }
                </FormItem>
                
            </Form>
        )
    }
}
RoleForm = Form.create({})(RoleForm)

class PreEditForm extends React.Component{

    renderTreeNodes = (data) =>{
        return data.map((item, index)=>{
            if(item.children){
                return <TreeNode title={item.title} key={item.key}>
                    {this.renderTreeNodes(item.children)}
                </TreeNode>
            }else {
                return <TreeNode {...item}></TreeNode>
            }
        })
    }

    onCheck=(checkedKeys)=>{
        this.props.patchMenuInfo(checkedKeys)
    }
    render(){
        const { getFieldDecorator } = this.props.form;
        //设置布局模式
        const FormLayout = {
            labelCol: {
                span: 5
            },
            wrapperCol: {
                span: 19
            }
        }
        const detail_Info = this.props.detailInfo;
        const menu_Info = this.props.menuInfo;
        return(
            <Form layout="horizontal">
                <FormItem label="角色名称" {...FormLayout}>
                    {
                        getFieldDecorator('role_name')(
                            <Input disabled placeholder={detail_Info.role_name} />
                        )
                    }
                </FormItem>
                <FormItem label="状态" {...FormLayout}>
                    {
                        getFieldDecorator('statu',{
                            initialValue: '1'
                        })(
                            <Select>
                                <Option value={1}>启用</Option>
                                <Option value={0}>停用</Option>
                            </Select>
                        )
                    }
                </FormItem>
                <Tree
                  checkable
                  defaultExpandAll  //默认展开所有树节点
                  onCheck={(checkedKeys)=>{
                      this.onCheck(checkedKeys)
                  }}
                  checkedKeys={menu_Info}
                  >
                    <TreeNode title="平台权限">
                        {this.renderTreeNodes(menuConfig)}
                    </TreeNode>
                </Tree>
            </Form>
        )
    }
}
PreEditForm = Form.create({})(PreEditForm)

class RoleAuthForm extends React.Component{
    filterOption = (inputValue, option) => {
        return option.title.indexOf(inputValue) > -1;
    }

    handleChange=(targetKeys)=> {
        this.props.disPatch(targetKeys)
    }
    render(){
        const { getFieldDecorator } = this.props.form;
        //设置布局模式
        const FormLayout = {
            labelCol: {
                span: 5
            },
            wrapperCol: {
                span: 19
            }
        }
        const detail_Info = this.props.detailInfo;
        // const menu_Info = this.props.menuInfo;
        return(
            <Form layout="horizontal">
                <FormItem label="角色名称" {...FormLayout}>
                    {
                        getFieldDecorator('role_name')(
                            <Input disabled placeholder={detail_Info.role_name} />
                        )
                    }
                </FormItem >
                <FormItem label="选择用户" {...FormLayout}>
                    <Transfer
                    listStyle={{width:200, height:400}}
                    dataSource={this.props.mockData}
                    targetKeys={this.props.targetKeys}
                    titles={['待选用户', '已选用户']}
                    onChange={this.handleChange}
                    showSearch
                    // locale='请输入用户名'
                    filterOption={this.filterOption}
                    render = {item => item.title}
                    />
                </FormItem>
            </Form>
        )
    }
}
RoleAuthForm = Form.create({})(RoleAuthForm)

export default Permission